#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while(true)
    {
        snprintf(buffer,sizeof(buffer),"I am child,pid: %d, cnt: %d",getpid(),cnt++);
        write(wfd,buffer,strlen(buffer));
        printf("child: %d\n",cnt);
        sleep(2);
        //break;
    }
}
void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        //sleep(5);
        buffer[0]=0;
        ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say: " << buffer <<std::endl;
        }
        //sleep(5);
        else if(n == 0)
        {
            std::cout <<"n : " << n<< std::endl;
            std::cout <<"child 退出，我也退出"<<std::endl;
            break;
        }
        else
        {
            break;
        }

        break;
    }
}
int main()
{
    // 1.创建管道
    int fds[2] = {0}; // fds[0]:读端  fds[1]:写端
    int n = pipe(fds);
    if (n < 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "fds[0]: " << fds[0] << std::endl;
    std::cout << "fds[1]: " << fds[1] << std::endl;

    // 2. 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        // 3.关闭不需要的读写端，形成通信信道
        close(fds[0]); // 子进程进行写，所以关闭读端
        ChildWrite(fds[1]);


        close(fds[1]);
        exit(0);
    }
    //parent
    close(fds[1]); // 父进程进行读，所以关闭写端
    FatherRead(fds[0]);
    close(fds[0]);

    sleep(5);
    int status = 0;
    int ret = waitpid(id, &status, 0);//获取子进程退出的信息！
    if(ret > 0)
    {
        printf("exit code: %d,exit signal: %d\n",(status>>8)&0xFF,status&0x7F);//0x7F为十进制数127 对应二进制数为：1111111
        sleep(5);
    }
    return 0;
}